import subprocess
import re

def get_eth0_ip():
    try:
        # 执行ifconfig命令并获取输出
        result = subprocess.run(['ifconfig', 'eth0'], capture_output=True, text=True, check=True)
        output = result.stdout

        # 使用正则表达式匹配IPv4地址
        ip_match = re.search(r'inet (\d+\.\d+\.\d+\.\d+)', output)
        if ip_match:
            return ip_match.group(1)
        else:
            return "127.0.0.1"
    except subprocess.CalledProcessError:
        print("❌ 无法执行ifconfig命令或eth0接口不存在")
        return "127.0.0.1"
    except Exception as e:
        print(f"⚠️ 获取eth0 IP失败: {e}, 使用默认127.0.0.1")
        return "127.0.0.1"

if __name__ == "__main__":
    # 获取并打印eth0的IP地址
    eth0_ip = get_eth0_ip()
    print(f"eth0的IP地址是: {eth0_ip}")
